<?php

namespace App\Http\Controllers\Api;
/*
use App\Models\File;
use App\Models\FileMapping;*/

use App\Repositories\Api\MemberRepository;
use App\Repositories\FileRepository;
use Illuminate\Http\Request;

class FileController extends MiniAppController
{
    public $fileRepo;

    public function __construct()
    {
        $this->fileRepo = new FileRepository();
    }

    /**
     * @param Request $request
     * 文件上传
     */
    public function upload(Request $request)
    {
        $objectType = $request->get('object_type', '');
        $objectId = $request->get('object_id', '');

        $field_key = request()->get("field_key");
        $fileData = request()->file('fileData', "");

        $subObjectKey = "";

        if (!$fileData) {
            return retFail("请选择要上传的文件");
        }

        $res = app(FileRepository::class)->upload($fileData, $objectType, $objectId, $subObjectKey);
        $res['size'] = formatBytes($res['size']);
        $res['full_path'] = getPreviewImage($res['full_path']);

        if ($field_key == 'avatar') {
            (new MemberRepository())->updateFields(UID, ['avatar' => $res['path']]);
        }

        return retSuc($res);
    }

    /**
     * @param Request $request
     * 文件下载
     */
    public function download(Request $request)
    {
        $fileId = $request->get('file_id', '');
        if (!$fileId) {
            return response([
                'code' => 400,
                'msg' => '参数错误',
                'data' => []
            ], 400);
        }

        $file = app(FileRepository::class)->getFileById($fileId);
        if (!$file) {
            return response([
                'code' => 400,
                'msg' => '文件不存在',
                'data' => []
            ], 400);
        }
        $path = $file->fullPath;

        if ($file) {
            /* 执行下载 *///TODO: 大文件断点续传
            header("Content-Description: File Transfer");
            header('Content-type: ' . $file['mimetype']);
            header('Content-Length:' . $file['size']);
            if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
                //for IE
                header('Content-Disposition: attachment; filename="' . rawurlencode($file['name']) . '"');
            } else {
                header('Content-Disposition: attachment; filename="' . $file['name'] . '"');
            }

            while (ob_get_level()) {
                ob_end_clean();
            }

            readfile($path);
            exit;
        }

    }

    /**
     * @param Request $request
     * 删除文件
     */
    public function delete()
    {
        $mid = request()->get('mid', 0);
        if (!$mid) {
            return response([
                'code' => 400,
                'msg' => '参数错误',
                'data' => []
            ], 400);
        }
        $ret = app(FileRepository::class)->removeMapFile($mid);
        return response()->json($ret);
    }
}
